﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using OptimumInfra.Models;
using OptimumInfra.ViewData;
using System.IO;

namespace OptimumInfra.Controllers
{
    public class TemplateController : Controller
    {
        //
        // GET: /Template/
        private TemplateRepository repo = new TemplateRepository();

        #region templates
        public ActionResult Index()
        {

            string message = Request.QueryString["step"];
            if (message != null || message == "")
                ViewData["message"] = "Step 1/3: Choose your server template";
            List<TemplateCategory> cats = this.repo.GetAllCategories();
            ViewData["cats"] = cats;
            foreach (TemplateCategory cat in cats)
            {
                List<ServerTemplate> templates = this.repo.GetTemplateByCat(cat.Id);
                string temp = "templates" + cat.Id.ToString();
                ViewData[temp] = templates;
            }
         //   ViewData["templates"] = this.repo.GetAllTemplates();
            return View(ViewData);
        }

        [Authorize(Roles = "admin")]
        public ActionResult Manage()
        {
            ViewData["templates"] = this.repo.GetAllTemplates();
            return View(ViewData);
        }

        public ActionResult Detail(int id)
        {
            ViewDataTemplate template = this.repo.GetTemplateById(id);
            return View(template);
        }

        //
        // GET: /ServiceSupport/Create
        [Authorize(Roles = "admin")]
        public ActionResult Create()
        {

             ViewDataTemplate service = new ViewDataTemplate();
            service.Categories = this.repo.GetAllCategories();
            return View(service);
        }

        //
        // POST: /ServiceSupport/Create

        [HttpPost]
        [Authorize(Roles = "admin")]
        public ActionResult Create(HttpPostedFileBase fileUpload)
        {
            
            try
            {
              
                // TODO: Add insert logic here
                ServerTemplate template = new ServerTemplate();
                string fileName = "";
                if (fileUpload != null && fileUpload.ContentLength != 0)
                {
                    fileName = "upload/" + Guid.NewGuid().ToString() + Path.GetExtension(fileUpload.FileName);
                    string folder = Request.PhysicalApplicationPath;
                    string linkAccess = Path.Combine(folder, fileName);
                    fileUpload.SaveAs(linkAccess);
                }
                UpdateModel(template);
                template.Image =  fileName;
                ServerTemplate temp = this.repo.CreateTemplate(template);
                TempData["info"] = "Create template successfully";
                return RedirectToAction("Edit", "Template", new { id = temp.Id });
            }
            catch(Exception e)
            {
                TempData["info"] = "Error occured";
                ViewDataTemplate service = new ViewDataTemplate();
                service.Categories = this.repo.GetAllCategories();
                return View(service);
            }
        }


        //
        // GET: /ServiceSupport/Edit/5
        [Authorize(Roles = "admin")]
        public ActionResult Edit(int id)
        {
            ViewDataTemplate template = this.repo.GetTemplateById(id);
            return View(template);
        }

        //
        // POST: /ServiceSupport/Edit/5

        [HttpPost]
        [Authorize(Roles = "admin")]
        public ActionResult Edit(int id, HttpPostedFileBase fileUpload)
        {
            try
            {
                // TODO: Add update logic here
                ViewDataTemplate template = new ViewDataTemplate();
                UpdateModel(template);
                ServerTemplate t = new ServerTemplate();
                t.Id = template.Id;
                t.Image = template.Image;
                t.Name = template.Name;
                t.Description = template.Description;
                t.Price = template.Price;
                t.Manufacturer = template.Manufacturer;
                t.CategoryId = template.CategoryId;
                string fileName = "";
                if (fileUpload != null && fileUpload.ContentLength != 0)
                {
                    fileName = "upload/" + Guid.NewGuid().ToString() + Path.GetExtension(fileUpload.FileName);
                    string folder = Request.PhysicalApplicationPath;
                    string linkAccess = Path.Combine(folder, fileName);
                    fileUpload.SaveAs(linkAccess);
                }
                t.Image = fileName;
                this.repo.UpdateTemplate(t);
                TempData["info"] = "Updated successfully";
                return RedirectToAction("Edit", "Template", new { id = id });
            }
            catch (Exception e)
            {
                TempData["info"] = "Error occured";
                return RedirectToAction("Edit", "Template", new { id = id });
            }
        }

        //
        // GET: /ServiceSupport/Delete/5
        [Authorize(Roles = "admin")]
        public ActionResult Delete(int id)
        {
            ServerTemplate template = this.repo.GetServerTemplateById(id);
            this.repo.DeleteTemplateById(template);
            return RedirectToAction("Manage");
        }

        #endregion
        #region template category
        //
        // GET: /ServiceSupport/Create

        public ActionResult Category()
        {


            string myList = Request.Form["ids"];
            if (myList == null || myList.Length == 0)
            {
                Response.Write("Nothing selected.");
            }
            else
            {
                foreach (string item in myList.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
                {
                    Response.Write(item + "<hr>");
                }
            }

            ViewData["categories"] = this.repo.GetAllCategories();
            return View(ViewData);
        }
        [Authorize(Roles = "admin")]
        public ActionResult CreateCategory()
        {

            TemplateCategory service = new TemplateCategory();
            return View(service);
        }

        //
        // POST: /ServiceSupport/Create

        [HttpPost]
        [Authorize(Roles = "admin")]
        public ActionResult CreateCategory(FormCollection collection)
        {
            try
            {
                // TODO: Add insert logic here
                TemplateCategory template = new TemplateCategory();
                UpdateModel(template);
                this.repo.CreateCategory(template);
                return RedirectToAction("Category");
            }
            catch
            {
                return View();
            }
        }


        //
        // GET: /ServiceSupport/Edit/5
        [Authorize(Roles = "admin")]
        public ActionResult EditCategory(int id)
        {
            TemplateCategory cat = this.repo.GetCategoryById(id);
            return View(cat);
        }

        //
        // POST: /ServiceSupport/Edit/5

        [HttpPost]
        [Authorize(Roles = "admin")]
        public ActionResult EditCategory(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add update logic here
               TemplateCategory cat = new TemplateCategory();
                UpdateModel(cat);
                this.repo.CreateCategory(cat);
                return RedirectToAction("Category");
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /ServiceSupport/Delete/5
         [Authorize(Roles = "admin")]
        public ActionResult DeleteCategory(int id)
        {
            TemplateCategory cat = this.repo.GetCategoryById(id);
            this.repo.DeleteCategoryById(cat);
            return RedirectToAction("Category");
        }
        #endregion

    }
}
